package com.um.springboot.starter.scheduled;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 *  按周期打印线程池执行器信息
 *
 * @author 甘天伟
 * @since 2024/7/5
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Component
@ConditionalOnExpression("${spring.task.print-executor-interval:0} > 0")
public class PrintExecutorTask {

    @Scheduled(fixedRateString = "${spring.task.print-executor-interval}",
            initialDelayString = "${spring.task.print-executor-interval}")
    public void scheduled() {
        StringBuilder sb = new StringBuilder();
        Map<String, ThreadPoolTaskExecutor> executors = SpringUtil.getBeansOfType(ThreadPoolTaskExecutor.class);
        executors.forEach((key, value) -> sb.append(StrUtil.format("\n{}: {}", key, value.getThreadPoolExecutor())));

        Map<String, ThreadPoolTaskScheduler> schedulers = SpringUtil.getBeansOfType(ThreadPoolTaskScheduler.class);
        schedulers.forEach((key, value) -> sb.append(StrUtil.format("\n{}: {}", key, value.getScheduledExecutor())));

        if (sb.length() > 0) {
            log.info(sb.toString());
        }
    }

}
